import { defineStore } from 'pinia';
import { reactive } from 'vue';

// setup
export const useAppStore = defineStore('app', () => {
    const state = reactive({
        lines: [],
        product: [],
        lMap: new Map(),
        pMap: new Map(),
    });

    const setLines = (newLines) => {
        if (!newLines) {
            state.lines = [];
            state.lMap.clear();
            return; 
        }
        state.lines = newLines;
        state.lMap.clear();

        newLines.forEach((line) => {
            state.lMap.set(line.code, line);
        });
    };

    const setProduct = (newProduct) => {
        if (!newProduct) {
            state.product = [];
            state.pMap.clear();
            return; 
        }
        state.product = newProduct;
        state.pMap.clear();
        newProduct.forEach((product) => {
            state.pMap.set(product.id, product);
        });
    };

    return {
        state,
        setLines,
        setProduct,
        getLineName: (id) => {
            return state.lMap.get(id)?.name;
        },
        getProductName: (id, model) => {
            const ps = state.pMap.get(id);
            if (!ps) {
                return '';
            }
            const n = ps.model.find(m => m.id === model)?.name

            return `${ps.name} - ${n}`;
        },
    };
});